<template>
  <el-card body-style="min-height: 86vh">
    <!-- 搜索 -->
    <el-form :model="searchForm" label-width="120">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="企业名称">
            <el-input v-model="searchForm.repairName" placeholder="请输入企业名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车主姓名">
            <el-input v-model="searchForm.customerName" placeholder="请输入车主姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车牌号码">
            <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送修日期">
            <el-date-picker
              v-model="searchForm.repairDate"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabled-date="handleDisabledDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-permission="['maintain:record:export']">
          <el-form-item label="所属区县">
            <el-select v-model="searchForm.areaCode" placeholder="请选择区县" clearable>
              <el-option
                v-for="item in areaList"
                :key="item.areaCode"
                :label="item.area"
                :value="item.areaCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button @click="handleRestSearch()">重置</el-button>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button
              v-permission="['maintain:record:export']"
              type="success"
              :loading="isExportLoading"
              @click="handleExport"
              >下载</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider />
    <!-- 新增、筛选按钮 -->
    <div class="flex justify-between">
      <div>
        <el-button v-permission="['maintain:record:add']" type="primary" @click="handleCreateRecord"
          >新增维修记录</el-button
        >
      </div>
      <div>
        <el-button circle @click="handleGetTableList()">
          <template #icon
            ><el-icon> <Refresh /> </el-icon
          ></template>
        </el-button>
      </div>
    </div>
    <el-table :data="tableData">
      <el-table-column
        label="企业名称"
        prop="repairName"
        min-width="160"
        align="center"
      ></el-table-column>
      <el-table-column
        label="车牌号"
        prop="licensePlate"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column label="车架号(vin)" prop="vin" width="200" align="center"></el-table-column>
      <el-table-column
        label="车主姓名"
        prop="customerName"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        label="联系方式"
        prop="customerPhone"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column label="送修日期" prop="repairDate" width="120" align="center">
        <template #default="{ row }">
          {{ dayjs(row.repairDate).format("YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 2 || row.status === 3 ? 'danger' : 'primary'">{{
            handleFilterStatus(row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" prop="remark" width="160" align="center"></el-table-column>
      <el-table-column label="操作" width="230" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" @click="handleLookHealthRecord(row)">查看</el-button>
          <el-button
            v-if="row.type === 2 && row.status !== 1"
            v-permission="['maintain:record:edit']"
            type="primary"
            @click="handleEditHealthRecord(row)"
            >编辑</el-button
          >
          <el-button
            v-if="row.status !== 1"
            v-permission="['maintain:record:upload']"
            type="primary"
            @click="handleUpload(row)"
            >上传</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex justify-center mt-2"
      background
      layout="total,prev, pager, next"
      :current-page="currentPage"
      :page-size="limit"
      :total="total"
      @current-change="handleGetTableList"
    />
    <form-dialog
      ref="formDrawerRef"
      :title="drawerTitle"
      width="98%"
      top="1vh"
      :isButton="isEdit"
      @submit="handleSubmitMaintain"
    >
      <div class="dialog-body">
        <el-divider content-position="left">客户信息</el-divider>
        <el-form ref="formRef" :model="form" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="车牌号" prop="licensePlate">
                <el-input
                  v-model="form.licensePlate"
                  :disabled="!isEdit"
                  placeholder="请输入车牌号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车架号(VIN)" prop="vin">
                <el-input v-model="form.vin" :disabled="!isEdit" placeholder="请输入车架号(VIN)" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户姓名" prop="customerName">
                <el-input
                  v-model="form.customerName"
                  :disabled="!isEdit"
                  placeholder="请输入客户姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户联系电话" prop="customerPhone">
                <el-input
                  v-model="form.customerPhone"
                  :disabled="!isEdit"
                  placeholder="请输入客户联系电话"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送修里程" prop="mileageNum">
                <el-input
                  v-model="form.mileageNum"
                  v-integer-number
                  type="number"
                  :min="1"
                  :disabled="!isEdit"
                  placeholder="请输入送修里程"
                  ><template #append>KM</template></el-input
                >
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送修日期" prop="repairDate">
                <el-date-picker
                  v-model="form.repairDate"
                  type="date"
                  placeholder="请选择送修日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  :disabled="!isEdit"
                  :disabled-date="handleDisabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结算日期" prop="settleDate">
                <el-date-picker
                  v-model="form.settleDate"
                  type="date"
                  placeholder="请选择结算日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  :disabled="!isEdit"
                  :disabled-date="handleDisabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="燃料(能源)类型" prop="energyType">
                <el-select
                  v-model="form.energyType"
                  placeholder="请选择燃料(能源)类型"
                  :disabled="!isEdit"
                >
                  <el-option
                    v-for="item in energyTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="故障描述" prop="failureDesc">
                <el-input
                  v-model="form.failureDesc"
                  placeholder="请输入故障描述"
                  :disabled="!isEdit"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider content-position="left">服务项目</el-divider>
        <div v-if="isEdit" class="flex justify-end mb-2">
          <el-button type="primary" @click="handleCreateProject()">添加项目</el-button>
        </div>
        <div class="dialog-project">
          <template v-if="form.projectList.length">
            <el-card class="mb-2" v-for="(item, index) in form.projectList" :key="item.projectName">
              <template #header>
                <div class="flex justify-between items-center">
                  <div>
                    <span class="font-bold text-base">{{ item.projectName }}</span>
                    <span class="ml-4"
                      >项目工时:<span>{{ item.duration }}</span>
                    </span>
                  </div>
                  <div v-if="isEdit">
                    <el-button type="primary" @click="handleAddAccessory(index)"
                      >添加配件</el-button
                    >
                    <el-popconfirm
                      title="确定删除该服务项目？"
                      width="200"
                      @confirm="handleDeleteProject(index)"
                    >
                      <template #reference><el-button type="danger">删除项目</el-button></template>
                    </el-popconfirm>
                  </div>
                </div>
              </template>
              <el-table :data="item.productList">
                <el-table-column label="配件名称" prop="productName"> </el-table-column>
                <el-table-column prop="productCode" label="配件编号" />
                <el-table-column prop="num" label="配件数量" />
                <el-table-column label="操作" v-if="isEdit">
                  <template #default="{ row, $index }">
                    <el-button type="primary" @click="handleEidtAccessoryBtn(row, index, $index)"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      title="确定删除该配件？"
                      width="200"
                      @confirm="handleDeleteAccessory(index, $index)"
                    >
                      <template #reference><el-button type="danger">删除</el-button></template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </template>
          <el-empty v-else description="暂无项目" />
        </div>
      </div>
      <!-- 添加项目 -->
      <form-drawer
        ref="formDrawerProjectRef"
        title="添加项目"
        :appendToBody="true"
        @submit="handleSumbitAddProject"
      >
        <el-form ref="formProjectRef" :model="formProject" :rules="rulesProject" label-width="120">
          <el-form-item label="维修项目" prop="projectName">
            <el-input v-model="formProject.projectName" placeholder="请输入维修项目" />
          </el-form-item>
          <el-form-item label="维修工时" prop="duration">
            <el-input
              v-model="formProject.duration"
              v-integer-number
              placeholder="请输入维修工时"
              type="number"
              :min="1"
            />
          </el-form-item>
        </el-form>
      </form-drawer>
      <!-- 添加配件 -->
      <form-drawer
        ref="formDrawerAccessoryRef"
        title="添加配件"
        :appendToBody="true"
        @submit="handleSubmitAddAccessory"
      >
        <el-form
          ref="formAccessoryRef"
          :model="formAccessory"
          :rules="rulesAccessory"
          label-width="120"
        >
          <el-form-item label="配件名称" prop="productName">
            <el-input v-model="formAccessory.productName" placeholder="请输入配件名称" />
          </el-form-item>
          <el-form-item label="配件编码" prop="productCode">
            <el-input v-model="formAccessory.productCode" placeholder="请输入配件编码" />
          </el-form-item>
          <el-form-item label="配件数量" prop="num">
            <el-input
              v-model="formAccessory.num"
              v-integer-number
              placeholder="请输入配件数量"
              type="number"
              :min="1"
            />
          </el-form-item>
        </el-form>
      </form-drawer>
    </form-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { useInitTable, useInitForm } from "@/hooks/useCommon";
import useDown from "@/hooks/useDown";
import {
  getMaintainRecordListApi,
  addEditMaintainRecordApi,
  uploadMaintainRecordApi,
  getMaintainRecordDetailApi,
  exportMaintainRecordApi
} from "@/api/maintain";
import { getAreaListApi } from "@/api/user";
import FormDialog from "@/components/FormDialog.vue";
import FormDrawer from "@/components/FormDrawer.vue";
import { energyTypeList } from "@/enum/index";
import { toast, showLoading, hideLoading } from "@/utils/index";
import { isCarNum } from "@/utils/regular";

const { tableData, searchForm, currentPage, limit, total, handleRestSearch, handleGetTableList } =
  useInitTable({
    searchForm: {
      repairName: "",
      customerName: "",
      licensePlate: "",
      repairDate: [],
      areaCode: ""
    },
    getTableList: getMaintainRecordListApi
  });

//搜索
const handleSearch = () => {
  if (searchForm.repairDate.length) {
    const endTime = searchForm.repairDate[1];
    searchForm.repairDate[1] = dayjs(endTime).format("YYYY-MM-DD 23:59:59");
  }
  handleGetTableList();
};

// 导出
const { downloadFile } = useDown();
const isExportLoading = ref(false);
const handleExport = async () => {
  try {
    isExportLoading.value = true;
    const res = await exportMaintainRecordApi({
      areaCode: searchForm.areaCode,
      startTime: searchForm.repairDate[0],
      endTime: searchForm.repairDate[1]
    });
    downloadFile(res as any, "电子健康档案.xlsx");
  } finally {
    isExportLoading.value = false;
  }
};

// 维修记录-弹框
let { formDrawerRef, formRef, form, rules, drawerTitle, handleCreate, handleEdit, handleSubmit } =
  useInitForm({
    form: {
      id: "",
      licensePlate: "",
      vin: "",
      customerName: "",
      customerPhone: "",
      mileageNum: "",
      repairDate: "",
      settleDate: "",
      energyType: "",
      failureDesc: "",
      projectList: []
    },
    rules: {
      licensePlate: [
        { required: true, message: "请输入车牌号", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!isCarNum(value)) {
              callback(new Error("请输入正确的车牌号"));
            } else {
              callback();
            }
          }
        }
      ],
      vin: [
        { required: true, message: "请输入车架号", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!value) {
              callback(new Error("请输入车架号"));
            } else if (!/^[A-Za-z0-9]{17}$/.test(value)) {
              callback(new Error("请输入正确的车架号"));
            } else {
              callback();
            }
          }
        }
      ],
      customerName: [{ required: true, message: "请输入客户姓名", trigger: "blur" }],
      customerPhone: [
        { required: true, message: "请输入客户电话", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            if (!value) {
              callback(new Error("请输入客户电话"));
            } else if (!/^1[3456789]\d{9}$/.test(value)) {
              callback(new Error("请输入正确的客户电话"));
            } else {
              callback();
            }
          }
        }
      ],
      mileageNum: [{ required: true, message: "请输入送修里程", trigger: "blur" }],
      repairDate: [{ required: true, message: "请选择送修日期", trigger: "blur" }],
      settleDate: [{ required: true, message: "请选择结算日期", trigger: "blur" }],
      energyType: [{ required: true, message: "请选择能源类型", trigger: "blur" }],
      failureDesc: [{ required: true, message: "请输入故障描述", trigger: "blur" }]
    },
    createData: addEditMaintainRecordApi,
    updateData: addEditMaintainRecordApi,
    success: () => {
      handleGetTableList();
    }
  });
// 项目-弹框
const {
  formDrawerRef: formDrawerProjectRef,
  formRef: formProjectRef,
  form: formProject,
  rules: rulesProject,
  handleCreate: handleCreateProject,
  handleSubmit: handleSumbitProject
} = useInitForm({
  form: {
    projectName: "",
    duration: ""
  },
  rules: {
    projectName: [{ required: true, message: "请输入维修项目", trigger: "blur" }],
    duration: [{ required: true, message: "请输入维修工时", trigger: "blur" }]
  },
  isRequest: true
});

// 配件-弹框
const {
  formDrawerRef: formDrawerAccessoryRef,
  formRef: formAccessoryRef,
  form: formAccessory,
  rules: rulesAccessory,
  handleCreate: handleCreateAccessory,
  handleEdit: handleEditAccessory,
  handleSubmit: handleSubmitAccessory
} = useInitForm({
  form: {
    productName: "",
    productCode: "",
    num: ""
  },
  rules: {
    productName: [{ required: true, message: "请输入配件名称", trigger: "blur" }],
    productCode: [{ required: true, message: "请输入配件编码", trigger: "blur" }],
    num: [{ required: true, message: "请输入配件数量", trigger: "blur" }]
  },
  isRequest: true
});

// 添加项目-确定
const handleSumbitAddProject = () => {
  (formProjectRef.value as any)?.validate((valid: boolean) => {
    if (valid) {
      // 表单验证通过
      form.projectList.push({
        projectName: formProject.projectName,
        duration: formProject.duration,
        productList: []
      });
      handleSumbitProject();
    }
  });
};
// 删除项目
const handleDeleteProject = (index: number) => {
  form.projectList.splice(index, 1);
};
// 配件是添加还是编辑
const isAccessoryEdit = ref(false);
// 当前要添加配件的项目index
const curProject = ref(0);
// 当前要添加配件的index
const curAccessory = ref(0);
// 添加配件-按钮
const handleAddAccessory = (index: number) => {
  curProject.value = index;
  isAccessoryEdit.value = false;
  handleCreateAccessory();
};

// 添加配件-确定
const handleSubmitAddAccessory = () => {
  const curItem = form.projectList[curProject.value].productList;
  if (isAccessoryEdit.value) {
    curItem[curAccessory.value] = {
      productName: formAccessory.productName,
      productCode: formAccessory.productCode,
      num: formAccessory.num
    };
  } else {
    curItem.push({
      productName: formAccessory.productName,
      productCode: formAccessory.productCode,
      num: formAccessory.num
    });
  }
  handleSubmitAccessory();
};
// 编辑配件
const handleEidtAccessoryBtn = (row: any, pindex: number, aindex: number) => {
  curAccessory.value = aindex;
  curProject.value = pindex;
  isAccessoryEdit.value = true;
  handleEditAccessory(row);
};
// 删除配件
const handleDeleteAccessory = (pindex: number, aindex: number) => {
  form.projectList[pindex].productList.splice(aindex, 1);
};

// 当前日期后面的时间不可选
const handleDisabledDate = (time: any) => {
  return time.getTime() > Date.now();
};

// 确定
const handleSubmitMaintain = () => {
  const curRepairDate = dayjs(form.repairDate).valueOf();
  const curSettleDate = dayjs(form.settleDate).valueOf();
  if (curRepairDate > curSettleDate) {
    return ElMessage({
      showClose: true,
      message: "结算日期不能小于送修日期",
      type: "warning"
    });
  }
  if (form.projectList.length <= 0) {
    return ElMessage({
      showClose: true,
      message: "至少添加一个服务项目",
      type: "warning"
    });
  }
  handleSubmit();
};
// 查看时禁用
const isEdit = ref(false);
// 查看
const handleLookHealthRecord = (row: any) => {
  isEdit.value = false;
  handleEidtRecord(row);
};
// 编辑
const handleEditHealthRecord = (row: any) => {
  isEdit.value = true;
  handleEidtRecord(row);
};
// 新增
const handleCreateRecord = () => {
  console.log(form.projectList);
  form.projectList && (form.projectList.length = 0);
  isEdit.value = true;
  handleCreate();
  
};

// 上传
const handleUpload = async (row: any) => {
  try {
    showLoading();
    await uploadMaintainRecordApi({ recordId: row.id });
    handleGetTableList();
  } catch (error) {
    toast("上传失败", "error");
  } finally {
    hideLoading();
  }
};

// 处理上传状态
const handleFilterStatus = (val: number) => {
  const statusMap: any = {
    0: "未上传",
    1: "上传成功",
    2: "上传失败",
    3: "上传异常"
  };
  return statusMap[val];
};

// 编辑
const handleEidtRecord = async (row: any) => {
  const res = await getMaintainRecordDetailApi({ id: row.id });
  handleEdit(res);
  (formDrawerRef.value as any).open();
};
// 获取区县列表
const areaList = ref<any>([]);
const handleGetAreaList = async () => {
  const res: any = await getAreaListApi();
  areaList.value = res;
};

onMounted(() => {
  handleGetAreaList();
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 180px);
  overflow-y: auto;
}

.dialog-project {
  height: calc(100vh - 480px);
  overflow-y: auto;
}
</style>
